`
https://leetcode.cn/problems/serialize-and-deserialize-bst/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function (root) {
  const preorder = []
  const _serialize = (root) => {
    if (root === null) return
    preorder.push(root.val)
    _serialize(root.left)
    _serialize(root.right)
  }
  _serialize(root)
  return preorder.join(',')
};

/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function (data) {
  if (data.length === 0) return null
  const nodes = data.split(',').map((n) => +n)

  const _deserialize = (min, max) => {
    if (nodes.length === 0) return null

    // 前序遍历位置进行反序列化
    // 前序遍历结果第一个节点是根节点
    const rootVal = nodes[0];
    if (rootVal > max || rootVal < min) {
      // 超过闭区间 [min, max]，则返回空指针
      return null;
    }
    nodes.shift();
    // 生成 root 节点
    const root = new TreeNode(rootVal);
    // 构建左右子树
    // BST 左子树都比根节点小，右子树都比根节点大
    root.left = _deserialize(min, rootVal);
    root.right = _deserialize(rootVal, max);

    return root;
  }
  return _deserialize(-Infinity, Infinity)
};

/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/